using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Graphics;

using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework;
using System.IO;

namespace WinXnaFE
{
    public class SpriteAnimation
    {
        public string Name;
        public List<Frame> Frames = new List<Frame>();

        Texture2D texture;
        public SpriteAnimation(ContentManager content, string fileName)
        {

            StreamReader sr = File.OpenText(fileName);

            Name = sr.ReadLine().Trim();

            texture = content.Load<Texture2D>(Name);

            int numFrames = int.Parse(sr.ReadLine().Trim());

            for (int i = 0; i < numFrames; i++)
            {
                string[] values = sr.ReadLine().Trim().Split(',');
                Frame f = new Frame();
                f.resource = values[0].Trim();
                f.x = int.Parse(values[1].Trim());
                f.y = int.Parse(values[2].Trim());
                f.width = int.Parse(values[3].Trim());
                f.height = int.Parse(values[4].Trim());
                f.delay = int.Parse(values[5].Trim());
                Frames.Add(f);
            }
            currentFrame = Frames[currentFrameIndex];
            sr.Close();
        }
        double currentDelay = 0;
        Frame currentFrame;
        int currentFrameIndex;

        public void Draw(SpriteBatch batch, double elapsedTime, Vector2 pos)
        {
            currentDelay += elapsedTime;
            if (currentDelay >= currentFrame.delay)
            {
                currentFrameIndex++;
                if (currentFrameIndex >= Frames.Count) currentFrameIndex = 0;
                currentFrame = Frames[currentFrameIndex];
                currentDelay = 0;
            }

            Microsoft.Xna.Framework.Rectangle src = new Microsoft.Xna.Framework.Rectangle(currentFrame.x, currentFrame.y, currentFrame.width, currentFrame.height);
            Microsoft.Xna.Framework.Rectangle dst = new Microsoft.Xna.Framework.Rectangle((int) pos.X, (int) pos.Y, currentFrame.width, currentFrame.height);
            batch.Draw(texture, dst, src, Color.White);
        }

        public class Frame
        {
            public string resource;
            public int x, y, width, height, delay;
        }




    }
}
